package com.eqdd.yiqidian.ui.discover.makerspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.*
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.utils.ImageUtil
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.io.Serializable
import java.util.*

/**
 * Created by jhj on 18-8-11.
 */
class MakerPhotoMenuActivity : BaseActivity() {
    var slimAdapterEx: SlimAdapterEx<MakerPhotoBean>? = null
    var mvcHelper: MVCCoolHelper<List<MakerPhotoBean>>? = null
    private var makerGuid: String? = null
    private var longClickData: MakerPhotoMenuActivity.MakerPhotoBean? = null

    override fun initBinding() {
        setContentView(R.layout.activity_recyclerview_refresh)
        initTopTitleBar(View.VISIBLE, "个人相册")
        makerGuid = intent.getStringExtra(Config.GUID)
        if (makerGuid == null) {
            return
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MVCCoolHelper.setLoadViewFractory(CustomLoadViewFactory().setShowFooter(true))
    }


    private var longClickPos: Int = 0

    override fun initData() {
        var pageNum = 0
        val density = resources.displayMetrics.density
        val screenWidth = resources.displayMetrics.widthPixels
        val photoSize = (screenWidth - density * 30) / 2
        val params = LinearLayout.LayoutParams(photoSize.toInt(), photoSize.toInt())
        val list = arrayListOf<MakerPhotoBean>()
        recyclerView.layoutManager = GridLayoutManager(this, 2)
        recyclerView.addItemDecoration(GridSpacingItemDecoration(2, 30, true));
        MVCCoolHelper.setLoadViewFractory(CustomLoadViewFactory().setShowFooter(false))
        mvcHelper = MVCCoolHelper<List<MakerPhotoBean>>(coolRefreshView)
        slimAdapterEx = SlimAdapterEx.create()
                .register<MakerPhotoBean>(R.layout.list_item_182, SlimInjector<MakerPhotoBean> { data, injector ->
                    if (data?.isAdd == true) {
                        injector
                                ?.with<LinearLayout>(R.id.layout_add) {
                                    it.layoutParams = params
                                }
                                ?.visible(R.id.layout_addg)
                                ?.gone(R.id.linearLayout)
                                ?.clicked(R.id.layout_add) {
                                    startActivityForResult<EditTextActivity>(1000, "title" to "相册名称", "tip" to "相册名称")
                                }

                    } else {
                        injector
                                ?.with<ImageView>(R.id.imageView) {
                                    it.layoutParams = params
                                    ImageUtil.setImage(data?.imageUrl, it)
                                }
                                ?.text(R.id.tv_name, data?.title)
                                ?.text(R.id.tv_count, String.format(Locale.CHINA, "%d张", data?.imageCount))
                                ?.visible(R.id.linearLayout)
                                ?.gone(R.id.layout_addg)
                    }

                })
                .attachTo(recyclerView)
                .updateData(list as List<MakerPhotoBean>?) as SlimAdapterEx<MakerPhotoBean>?
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener { recyclerView, position, v ->
                    startActivityForResult<MakerPhotoActivity>(1002, "makerGuid" to makerGuid,
                            Config.ID to slimAdapterEx?.getDataItem(position)?.Id,
                            Config.TITLE to slimAdapterEx?.getDataItem(position)?.title)
                }
                .setOnItemLongClickListener { recyclerView, position, v ->
                    longClickData = slimAdapterEx?.getDataItem(position)
                    longClickPos = position
                    bottomDialog(arrayListOf("修改相册名称", "删除相册")) {
                        when (it) {
                            1 -> {
                                startActivityForResult<EditTextActivity>(1001, "title" to "相册名称", "tip" to "相册名称", "content" to longClickData?.title)
                            }
                            2 -> {
                                deleteDialog(HttpConfig.BASE_URL + HttpConfig.PHOTO_MENU_DELETE, "是否删除“${longClickData?.title}”？", "menuId" to longClickData?.Id, isFinish = false) {
                                    slimAdapterEx?.data?.removeAt(position)
                                    slimAdapterEx?.notifyItemRemoved(position)
                                }
                            }
                        }
                    }
                    true
                }

        val dataSource = ModelRx2DataSource<MakerPhotoBean>(ModelRx2DataSource.OnLoadSource<MakerPhotoBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResultRows<MakerPhotoBean>>(HttpConfig.BASE_URL + HttpConfig.PHOTO_MENU_LIST)
                    .params("page", pageNum)
                    .params("lectureGuid", makerGuid)
                    .converter(object : JsonConverter<HttpResultRows<MakerPhotoBean>>() {
                        override fun test() {
                            super.test()
                        }
                    })
                    .adapt(FlowableBody<HttpResultRows<MakerPhotoBean>>())
                    .flatMap { result ->
                        if (page == 1) {
                            mvcHelper?.isAutoLoadMore = true
                        }
                        pageNum = result.items.page

                        val dataList = result.items.rows ?: arrayListOf<MakerPhotoBean>()
                        if (pageNum == 1) {
                            val bean = MakerPhotoBean()
                            bean.isAdd = true
                            dataList.add(0, bean)
                        }

                        Flowable.just<MutableList<MakerPhotoBean>>(
                                dataList as MutableList<MakerPhotoBean>?
                                        ?: mutableListOf<MakerPhotoBean>()
                        )
                    }

        }, 9)
        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()


    }

    override fun setView() {

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (Config.INTENT_CONTENT == resultCode) {
            val str = data?.getStringExtra("content")
            if (1000 == requestCode) {
                OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.PHOTO_MENU_ADD)
                        .params("userGuid", makerGuid)
                        .params("title", str)
                        .execute(object : DialogCallBack<HttpResult<*>>(this) {
                            override fun onSuccess(response: Response<HttpResult<*>>?) {
                                val result = response?.body()
                                if (result?.status == 200) {
                                    toast("新增成功")
                                    mvcHelper?.refresh()
                                } else {
                                    toast(result?.msg ?: "新增失败")
                                }
                            }
                        })
            } else if (1001 == requestCode) {
                OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.PHOTO_MENU_NAME_UPDATE)
                        .params("userGuid", makerGuid)
                        .params("menuName", str)
                        .params("menuId", longClickData?.Id ?: 0)
                        .execute(object : DialogCallBack<HttpResult<*>>(this) {
                            override fun onSuccess(response: Response<HttpResult<*>>?) {
                                val result = response?.body()
                                if (result?.status == 200) {
                                    slimAdapterEx?.getDataItem(longClickPos)?.title = str
                                    slimAdapterEx?.notifyItemChanged(longClickPos)
                                } else {

                                }
                            }
                        });
            }
        }

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1002) {
                mvcHelper?.refresh()
            }
        }

    }

    class MakerPhotoBean : Serializable {
        //左侧图片
        var Id: Int = 0
        var creater: String? = null
        var title: String? = null
        var imageUrl: String? = null
        var imageCount: Int = 0
        var isAdd: Boolean = false//设置新增图片

    }
}